from django.db import models
from django.utils.timezone import now

from api.conf import order_status
from foodmarket.settings import MEDIA_HOST
from .address import MailingAddress
from .fm_user import FMUser
from .pay_method import PayMethod
from .product import ProductSpec


class Order(models.Model):
    created_datetime = models.DateTimeField(verbose_name=u'订单生成时间', default=now)
    expired_datetime = models.DateTimeField(verbose_name=u'订单过期时间', null=True, blank=True)
    user = models.ForeignKey(FMUser, verbose_name=u'下单用户', related_name='orders')
    status = models.IntegerField(choices=order_status.CHOICES, default=order_status.NOT_PAYED, verbose_name=u'订单状态')
    sum = models.IntegerField(verbose_name=u'金额', default=0)
    remark = models.TextField(default='', blank=True, null=True, verbose_name=u'备注')
    address = models.ForeignKey(MailingAddress, null=True, blank=True, verbose_name=u'邮寄地址')
    delivery_datetime = models.DateTimeField(verbose_name=u'配送时间', null=True, blank=True)
    delivery_deadline_datetime = models.DateTimeField(verbose_name=u'最迟配送时间', null=True, blank=True)
    pay_method = models.ForeignKey(PayMethod, verbose_name=u'支付方式', null=True, blank=True)
    out_order_id = models.CharField(max_length=30, verbose_name=u'订单号')
    deposit = models.PositiveIntegerField(default=0, verbose_name=u'押金')

    class Meta:
        verbose_name = u'订单'
        verbose_name_plural = u'订单'

    @property
    def 销售(self):
        if self.user:
            return self.user.sales
        return None

    @property
    def 支付方式(self):
        if self.pay_method:
            return self.pay_method.name
        return None


class OrderProduct(models.Model):
    order = models.ForeignKey(Order, related_name='products')
    spec = models.ForeignKey(ProductSpec, default=None, blank=True, null=True)
    product_name = models.CharField(max_length=30, verbose_name=u'商品名称')
    spec_name = models.CharField(max_length=30, verbose_name=u'规格')
    price = models.IntegerField(verbose_name=u'价格')
    discount = models.IntegerField(null=True, blank=True, verbose_name=u'优惠价格')
    unit = models.CharField(max_length=30, verbose_name=u'单位')
    amount = models.IntegerField(verbose_name=u'数量')
    image = models.ImageField(verbose_name=u'图片', blank=True, null=True)
    deposit = models.PositiveIntegerField(default=0, verbose_name=u'押金')
    deposit_desc = models.CharField(max_length=30, null=True, blank=True, verbose_name=u'押金说明')

    @property
    def image_url(self):
        try:
            return MEDIA_HOST + self.image.url
        except ValueError:
            return ''

    class Meta:
        verbose_name = u'订单商品'
        verbose_name_plural = u'订单商品'

    def __str__(self):
        return '%s - %s' % (self.product_name, self.spec_name)
